package com.cyx.netty.n7;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;

/*
对比jdk的Future、netty的Future和netty的Promise
 */
@Slf4j
public class TestNettyPromise {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1.准备EventLoop对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop eventLoop = group.next();
        // 2.可以主动创建Promise 结果容器
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);

        new Thread(() -> {
            // 3.任意一个线程执行计算，计算完毕后向Promise填充结果
            log.info("开始计算...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            promise.setSuccess(50);
        }).start();

        // 4.接受结果的线程
        log.info("等待结果...");
        // 同步阻塞，等待计算结果
//        log.info("result {}", promise.get());
        // 异步方式
        promise.addListener(future -> {
            log.info("result {}", promise.get());
            group.shutdownGracefully();
        });
    }
}
